package cn.wolfcode.wolf2w.web.controller;

import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.cache.service.IVisitorRedisService;
import cn.wolfcode.wolf2w.cache.vo.VisitorVo;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.domain.Visitor;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.service.IVisitorService;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("visitor")
public class VisitorController {
    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IVisitorRedisService visitorRedisService;


    @RequestMapping("get")
    public Object get(String id){

        UserInfo userInfo = userInfoService.get(id);

        return JsonResult.success(userInfo);
    }

    @RequestMapping("getVisitors")
    public Object getVisitors(String id, @UserParam UserInfo userInfo){
        HashMap<String,Object> map = new HashMap<>();
        // 当我访问别人的时候
        if(!id.equals(userInfo.getId())){
            // 累计访问数+1 并 将访问者id加入游客id集合中
            visitorRedisService.totalViewIncr(id,userInfo.getId());
        }

        // 通过游客的id获取对应的vo对象
        VisitorVo vo = visitorRedisService.queryVisitorVo(id);
        // 创建一个收集游客信息的集合
        List<UserInfo> list = new ArrayList<>();
        // 通过访问游客的id，获取对应的对象信息
        List<String> visitorIds = vo.getVisitorIds();
        for (String vid : visitorIds){
            // 查询得到所有游客对象信息
            UserInfo user = userInfoService.get(vid);
            list.add(user);
        }

        // 截取最新访客前8位
        if(list.size()>8){
            Collections.reverse(list);
            list = list.subList(0, 8);
        }

        // 通过当前页面用户的id，获取对应的游客访问信息
        //List<UserInfo> list = visitorService.queryForVisitor(id);


        if (!id.equals(userInfo.getId())){
            // 对今日访问数+1
            visitorRedisService.todayViewIncr(id,1);
        }
        // 获取今日访问数
        int todayView = visitorRedisService.queryTodayView(id);

        map.put("visitors",list);
        map.put("vo",vo);
        map.put("todayView",todayView);
        return JsonResult.success(map);
    }

    @RequestMapping("list")
    public Object list(String id){
       //List<UserInfo> users = visitorService.queryForVisitor(id);

        // 浏览更多自己的游客访问信息
        List<UserInfo> users =  visitorRedisService.queryForVisitorIds(id);
        return JsonResult.success(users);
    }



}
